/**
 * zoneland.net Inc.
 * Copyright (c) 2002-2012 All Rights Reserved.
 */
package com.sanerzone.smscenter.biz.listener;

import com.sanerzone.common.support.sequence.CachedMillisecondClock;
import com.sanerzone.smscenter.biz.message.SMSMOMessage;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSRTMessage;
import com.sanerzone.smscenter.gateway.GatewayStartUp;
import com.sanerzone.smscenter.gateway.http.HttpGatewayFactory;
import com.sanerzone.smscenter.gateway.ums.MoListener;
import com.sanerzone.smscenter.gateway.ums.comm.PMessage;
import com.sanerzone.smscenter.gateway.ums.comm.cmpp.message.CMPPDeliverMessage;
import com.sanerzone.smscenter.gateway.ums.comm.smgp3.message.SMGP3DeliverMessage;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;

import java.io.Serializable;
import java.util.Map;

public class UmsMOListener implements MoListener, InitializingBean {

    private static Logger       logger = Logger.getLogger("UMS-GATEWAY-MO");

    /**
     * @see com.sanerzone.smscenter.gateway.ums.MoListener#OnTerminate()
     */
    public void OnTerminate() {
    }

    /**
     * @see com.sanerzone.smscenter.gateway.ums.MoListener#onDeliver(com.sanerzone.smscenter.gateway.ums.comm.PMessage,
     *      Map)
     */
    public void onDeliver(PMessage arg0, Map<String, String> arg1) {
        if (logger.isInfoEnabled()) {
            logger.info("收到上行短信:" + arg0);
        }
        String gateWayID = arg1.get("gatewayId");
        if (arg0 instanceof SMGP3DeliverMessage) {
			SMGP3DeliverMessage e = (SMGP3DeliverMessage) arg0;
			if (e.getIsReport() == 1) {
				SMSRTMessage message = new SMSRTMessage();
//	    		message.setDestTermID(e.getSrcTermID());
//	    		message.setSrcTermID(e.getDestTermID());
				message.setDoneTime(e.getDoneTime());
				message.setSubmitTime(e.getSubTime());
				message.setMsgid(e.getReportMsgID());
				message.setSmscSequence("1");
				Serializable mtMsg = HttpGatewayFactory.getStoredMap().remove(e.getReportMsgID());
				if (mtMsg != null)
					message.setSmsMt((SMSMTMessage) mtMsg);
				message.setStat(String.valueOf(e.getStat()));
				GatewayStartUp.httpGateWayMessage.sendSmsRTMessage(message, gateWayID);
			} else {
				SMSMOMessage message = new SMSMOMessage();
//        		message.setDestTermID(e.getSrcTermID());
//        		message.setSrcTermID(e.getDestTermID());
				message.setMsgid(e.getMsgID());
				message.setMsgContent(e.getMsgContentStr());
				GatewayStartUp.httpGateWayMessage.sendSmsMOMessage(message, gateWayID);
			}

		}else if (arg0 instanceof CMPPDeliverMessage) {
			CMPPDeliverMessage deliverMsg = (CMPPDeliverMessage) arg0;
			if (deliverMsg.getRegisteredDeliver() == 0) {
				try {
					// 编码方式
					if (deliverMsg.getMsgFmt() == 8) {
						logger.debug("deliverMsg.getMsgFmt() == 8");
						logger.debug(String.valueOf(String.valueOf((new StringBuffer(
								"接收消息: 主叫号码=")).append(
								deliverMsg.getSrcterminalId()).append(";内容=").append(
								new String(deliverMsg.getMsgContent(),
										"UTF-16BE")))));
						SMSMOMessage smsMoMessage = new SMSMOMessage();
						smsMoMessage.setSpnumber(deliverMsg.getDestnationId());
						smsMoMessage.setPhone(deliverMsg.getSrcterminalId());
						smsMoMessage.setMsgContent(new String(deliverMsg.getMsgContent(),"UTF-16BE"));
						smsMoMessage.setMsgid(PMessage.getMsgIdStr(deliverMsg.getMsgId()));
						smsMoMessage.setGateWayID(gateWayID);
						GatewayStartUp.httpGateWayMessage.sendSmsMOMessage(smsMoMessage, gateWayID);
					}
					// 编码方式GBK
					else {
						logger.debug(String.valueOf(String.valueOf((new StringBuffer(
								"接收消息: 主叫号码=")).append(
								deliverMsg.getSrcterminalId()).append(";内容=")
								.append(new String(deliverMsg.getMsgContent())))));
						SMSMOMessage smsMoMessage = new SMSMOMessage();
						smsMoMessage.setSpnumber(deliverMsg.getDestnationId());
						smsMoMessage.setPhone(deliverMsg.getSrcterminalId());
						smsMoMessage.setMsgContent(new String(deliverMsg.getMsgContent()));
						smsMoMessage.setMsgid(PMessage.getMsgIdStr(deliverMsg.getMsgId()));
						smsMoMessage.setGateWayID(gateWayID);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				/*logger.debug(String.valueOf(String.valueOf((new StringBuffer(
						"收到状态报告消息： stat="))
						.append(new String(deliverMsg.getStat())).append(
								"dest_termID=").append(
								new String(deliverMsg.getDestTerminalId())).append(
								";destterm=").append(
								new String(deliverMsg.getDestnationId())).append(
								";serviceid=").append(
								new String(deliverMsg.getServiceId())).append(
								";tppid=").append(deliverMsg.getTpPid()).append(
								";tpudhi=").append(deliverMsg.getTpUdhi()).append(
								";msgfmt").append(deliverMsg.getMsgFmt()).append(
								//";内容").append(new String(deliverMsg.getMsgContent())).append(
								";srctermid=").append(
								new String(deliverMsg.getSrcterminalId())).append(
								";deliver=").append(
								deliverMsg.getRegisteredDeliver()))));
				System.out.println(String.valueOf(String.valueOf((new StringBuffer(
						"收到状态报告消息： stat="))
						.append(new String(deliverMsg.getStat())).append(
								"dest_termID=").append(
								new String(deliverMsg.getDestTerminalId())).append(
								";destterm=").append(
								new String(deliverMsg.getDestnationId())).append(
								";serviceid=").append(
								new String(deliverMsg.getServiceId())).append(
								";tppid=").append(deliverMsg.getTpPid()).append(
								";tpudhi=").append(deliverMsg.getTpUdhi()).append(
								";msgfmt").append(deliverMsg.getMsgFmt()).append(
								//";内容").append(new String(deliverMsg.getMsgContent())).append(
								";srctermid=").append(
								new String(deliverMsg.getSrcterminalId())).append(
								";deliver=").append(
								deliverMsg.getRegisteredDeliver()))));*/
				SMSRTMessage smsRtMessage = new SMSRTMessage();
				smsRtMessage.setGateWayID(gateWayID);
				smsRtMessage.setMsgid(PMessage.getMsgIdStr(deliverMsg.getMsgId()));
				smsRtMessage.setPhone(deliverMsg.getSrcterminalId());
				smsRtMessage.setStat(deliverMsg.getStat());
				smsRtMessage.setSubmitTime(DateFormatUtils.format(CachedMillisecondClock.INS.now(), "yyMMddHHmmss"));
				smsRtMessage.setDoneTime(DateFormatUtils.format(CachedMillisecondClock.INS.now(), "yyMMddHHmmss"));
				smsRtMessage.setSpnumber(deliverMsg.getDestnationId());
				smsRtMessage.setSmscSequence(deliverMsg.getServiceId());
				SMSMTMessage message = (SMSMTMessage) HttpGatewayFactory.getStoredMap().remove(PMessage.getMsgIdStr(deliverMsg.getMsgId()));
				if (message != null) {
					smsRtMessage.setSmsMt(message);
					smsRtMessage.setMtBatchNum(message.getMtBatchNum());
				}
				smsRtMessage.setSmscSequence(deliverMsg.getServiceId());
				GatewayStartUp.httpGateWayMessage.sendSmsRTMessage(smsRtMessage, gateWayID);
			}
//		}else if (arg0 instanceof CMPPDeliverMessage) {

		} else {
			logger.error("接收到上行未知类型消息:" + arg0);
		}

	}

    /**
     * @see com.sanerzone.smscenter.gateway.ums.MoListener#onReport(com.sanerzone.smscenter.gateway.ums.comm.PMessage)
     */
    public PMessage onReport(PMessage arg0) {
    	System.out.println("-----------------------------------------------------收到短信报告-------------------------------------------------------------------------------------------------");
        return null;
    }

    /**
     * 默认的就db2;
     * @see InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet() throws Exception {
		System.out.println("-----------------------------------------------------收到短信报告222222-------------------------------------------------------------------------------------------------");

	}


	private String append86(String phone){
		if(StringUtils.startsWith(phone, "86"))
			return phone;
		return String.format("86%s", phone);
	}
	
	public static void main(String[] args) {
		switch(0) {
		case 0:
		case 1:
			System.out.println("DELIVRD");
			break;
		default:
			System.out.println("=======");
			break;
		}
	}
}
